import api from "/api.js";
import network from '/network.js';

/** 
 * 登陆 
 * @return {Promise}  
 */
function login() {
    return new Promise((resolve, reject) => wx.login({
        success: resolve,
        fail: reject
    }));
}

/** 
 * 获取用户信息 
 * @return {Promise}  
 */
function saveUserInfo(network, url, userInfo) {
    return new Promise((resolve, reject) => wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
            userInfo.avatar = res.userInfo.avatarUrl;
            userInfo.name = res.userInfo.nickName;
            userInfo.sex = res.userInfo.gender;
            network.postJson(url, userInfo).then(res => {
                resolve(userInfo);
            })
        },
        fail: reject
    }));
}

/** 
 * 获取用户信息 
 * @return {Promise}  
 */
function getSetting() {
    return new Promise((resolve, reject) => wx.getSetting({
        success: resolve,
        fail: reject
    }));
}

/** 
 * 解析微信上手机号 
 * @return {Promise}  
 */
function getPhoneNumber(that, e, id, isBack = false) {
    let _this = this;
    wx.checkSession({
        success() {
            //session_key 未过期，并且在本生命周期一直有效
            _this.decodedPhone(that, e, id, getApp().globalData.sessionCode, isBack);
        },
        fail() {
            // session_key 已经失效，需要重新执行登录流程
            wx.login({
                success(res) {
                    if (res.code) {
                        _this.decodedPhone(that, e, id, res.code, isBack);
                    }
                }
            })
        }
    })
}

/** 
 * 解析微信上手机号
 * @return {Promise}  
 */
function decodedPhone(that, e, id, code, isBack = false) {
    console.log(e)
    console.log(code)
    wx.cloud.callFunction({
        name: 'session',
        data: {
            session_code: code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
        }
    }).then(res => {
        console.log(res)
        return network.postJson(that, api.saveUserInfo, {
            user_id: id,
            phone: res.result.phoneNumber
        })
    }).then(res => {
        that.setData({
            user: res.data.data
        })

        if (isBack) {
            wx.navigateBack()
        }

        getApp().globalData.userInfo = res.data.data;
        that.toast.showToast("手机号获取成功");
    })
}

/** 
 * 读取app.js用户信息 
 * 此方法主要是为了避免重复写回调来读取已从服务器上获取到的用户信息
 */
function getAppUser(app, fun) {
    if (app.globalData.userInfo) {
        fun(app.globalData.userInfo);
    } else {
        app.userInfoReadyCallback = res => {
            fun(res);
        }
    }
}


/** 
 * 分享绑定
 * @return {Promise}  
 */
function sharebind(that, app, sub_id, activity_id) {
    app.getMidouUserInfo().then(user => {
        if (user.id != sub_id) {
            network.postJson(that, api.sharebind, {
                user_id: user.id,
                share_user_id: sub_id,
                activity_id: activity_id
            })
        }
    }).then(res => {})
}

/** 
 * 返回到指定页面
 */
function navigateBackPage(url) {
    let pages = getCurrentPages();
    console.log(pages)
    let pageSize = pages.length;
    let index = 1;
    for (let i = 0; i < pageSize; i++) {
        if (pages[i].router == url) {
            index = i;
        }
    }
    let delta = pageSize - index - 1;
    wx.navigateBack({
        delta: delta > 0 ? delta : 1
    })
}

module.exports = {
    login: login,
    saveUserInfo: saveUserInfo,
    navigateBackPage: navigateBackPage
}